package cn.com.user.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.cabinet.service.UserServiceImpl;
import cn.com.easy.utils.CookieUtils;

@Controller
@RequestMapping("/login")
public class UserLoginController {

	@Autowired
	private UserServiceImpl uService;
	
	
	@RequestMapping()
	public String login(HttpServletRequest request) throws Exception{
		String userid = CookieUtils.getCookieValue(request, "userid");
		if(userid == "null" || userid == null){
			//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e30694be5bcf4aa&redirect_uri=http://beckjo.xicp.net/wechat/login&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
			return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e30694be5bcf4aa&redirect_uri=http://www.yoyorv.cn/wechat/login&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
		}else{
			return "/index/index";
		}
		
	}

	@RequestMapping("/loginCheck")
	public String loginCheck(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap,String account , String password) throws Exception{
		String userid = CookieUtils.getCookieValue(request, "userid");
		if(userid == "null" || userid == null){
			if(uService.userLogin(account, password)){
				//设置cookie
				CookieUtils.setCookie(request, response, "userid",uService.getUser(account, password).getId().toString());
				//System.out.println(CookieUtils.getCookieRedirectUrl(request));
				return "redirect:"+CookieUtils.getCookieRedirectUrl(request);
			}else{
				//System.out.println("false");
				modelMap.addAttribute("loginMessage", "账号不存在或密码不正确！");
				return "/user/user_login";
			}
		}else{
			return "redirect:"+CookieUtils.getCookieRedirectUrl(request);
		}
	
		
	}
	
	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Cookie cookie = CookieUtils.getCookie(request, "userid");
		CookieUtils.deleteCookie(request, response, cookie);
		return "redirect:/index";
	}
}
